const express = require('express');
const router = express.Router();
const query = require('../config/db');

// 搜索
router.get('/search', async (req, res, next) => {
    // 取出前端的关键字
    let { kw = '', page = 1, size = 10 } = req.query;
    // 转换为number
    page=Number(page);
    size=Number(size);
    // 判断关键字不能为空
    if(kw == ''){
        next('请输入关键字');
        return;
    }
    // 有关键字
    // 查询和关键词相关的所有数据
    let sql1 = `select * from e_course where title like '%${kw}%' or area_name like '%${kw}%' or grade_name like '%${kw}%' or subject_name like '%${kw}%' or
    category_name like '%${kw}%'`;
    let result1 = await query(sql1);

    // 总条数
    let totalNum = result1.length;

    // 总页数
    let totalPage = Math.ceil(totalNum / size)

    // 第page页的size条数据 
    let sql2 = `select * from e_course where title like '%${kw}%' or area_name like '%${kw}%' or grade_name like '%${kw}%' or subject_name like '%${kw}%' or
    category_name like '%${kw}%' limit ${(page - 1) * size},${size}`;
    let result2 = await query(sql2);

    // 1.7返回给前端
    res.send({
        success: true,
        msg: "查询成功",
        status: 200,
        data: {
            totalPage,
            totalNum,
            // 数据
            list: result2,
            // 当前页码
            page
        }
    })
})

module.exports = router;